<script setup>
import { ref } from 'vue'
import { carPageQueryService, deleteCarService } from '@/api/car.js'
import {
  Search,
  Refresh,
  Edit,
  Delete,
  DCaret,
  CaretTop,
  CaretBottom
} from '@element-plus/icons-vue'
import CarEdit from './components/CarEdit.vue'
import { useUserStore } from '@/stores'

// 获取用户角色
const userStore = useUserStore()
const userRole = userStore.user.role

const carList = ref([]) // 车辆列表
const total = ref(0) // 总条数
const loading = ref(false) // loading状态

// 请求参数
const params = ref({
  pageNum: 1, // 当前页码
  pageSize: 10, // 每页条数
  orderBy: 'update_time', // 排序字段
  isAsc: false, // 是否升序
  name: null, // 会员姓名
  plateNumber: null, // 车牌号
  brand: null, // 车辆品牌
  model: null // 车辆型号
})

// 基于params参数，获取车辆列表
const getCarList = async () => {
  loading.value = true
  const res = await carPageQueryService(params.value)
  carList.value = res.data.data.list
  total.value = res.data.data.total
  loading.value = false
}
getCarList()

// 处理分页逻辑
const onPageSizeChange = (size) => {
  params.value.pageNum = 1
  params.value.pageSize = size
  getCarList()
}
const onPageNumChange = (page) => {
  params.value.pageNum = page
  getCarList()
}

// 处理排序逻辑
const handleSort = (field) => {
  if (params.value.isAsc === false && params.value.orderBy === field) {
    // 如果当前已经降序，则重置排序
    params.value.orderBy = null
    params.value.isAsc = null
  } else if (params.value.orderBy === field) {
    // 如果当前已经是按该字段排序，则切换升序/降序
    params.value.isAsc = !params.value.isAsc
  } else {
    // 如果是第一次点击该字段，则默认升序
    params.value.orderBy = field
    params.value.isAsc = true
  }
  // 重新获取数据
  getCarList()
}

// 获取排序图标
const getSortIcon = (field) => {
  if (params.value.orderBy === field) {
    return params.value.isAsc ? CaretTop : CaretBottom
  }
  return DCaret
}

// 显示会员信息
const activeMemberId = ref() // 当前需要显示的会员ID
const showMemberInfoForm = (memberId) => {
  activeMemberId.value = memberId
}

// 搜索逻辑
const handleSearch = () => {
  params.value.pageNum = 1
  getCarList()
}

// 重置逻辑
const handleReset = () => {
  params.value = {
    ...params.value, // 保留其他属性
    pageNum: 1,
    name: null,
    plateNumber: null,
    brand: null,
    model: null
  }
  getCarList()
}

const carEditRef = ref()
// 新增逻辑
const handleAdd = () => {
  carEditRef.value.open({})
}

// 编辑逻辑
const handleEdit = (row) => {
  carEditRef.value.open(row)
}

// 删除逻辑
const handleDelete = async (row) => {
  await ElMessageBox.confirm('是否确认删除该车辆？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deleteCarService(row.id)
  ElNotification({
    title: '删除成功',
    type: 'success'
  })
  getCarList()
}
</script>

<template>
  <page-container title="车辆管理">
    <template #extra>
      <el-button
        v-if="['管理员', '店长'].includes(userRole)"
        type="primary"
        plain
        @click="handleAdd"
        >新增车辆</el-button
      >
    </template>
    <!-- 表单 -->
    <el-form inline>
      <el-form-item label="会员姓名:"
        ><el-input v-model="params.name" placeholder="请输入"
      /></el-form-item>
      <el-form-item label="车牌号:"
        ><el-input v-model="params.plateNumber" placeholder="请输入"
      /></el-form-item>
      <el-form-item label="车辆品牌:"
        ><el-input v-model="params.brand" placeholder="请输入"
      /></el-form-item>
      <el-form-item label="车辆型号:"
        ><el-input v-model="params.model" placeholder="请输入"
      /></el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleSearch"></el-button>
        <el-button type="default" :icon="Refresh" @click="handleReset"></el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table class="tb" :data="carList" v-loading="loading" :row-style="{ height: '50px' }">
      <el-table-column prop="id" label="车辆ID" width="150">
        <template #header>
          <span>车辆ID</span>
          <el-icon @click="handleSort('id')">
            <component :is="getSortIcon('id')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="memberId" label="会员ID" width="180">
        <template #header>
          <span>会员ID</span>
          <el-icon @click="handleSort('member_id')">
            <component :is="getSortIcon('member_id')" />
          </el-icon>
        </template>
        <template #default="{ row }">
          <el-popover effect="light" trigger="click" placement="right" :width="600">
            <template #reference>
              <el-tag @click="showMemberInfoForm(row.memberId)">{{ row.memberId }}</el-tag>
            </template>
            <MemberInfoForm v-if="activeMemberId === row.memberId" :memberId="row.memberId" />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="plateNumber" label="车牌号" width="180" />
      <el-table-column prop="brand" label="车辆品牌" width="180" />
      <el-table-column prop="model" label="车辆型号" width="180" />
      <el-table-column prop="lastServiceTime" label="上次服务时间" width="180">
        <template #header>
          <span>上次服务时间</span>
          <el-icon @click="handleSort('last_service_time')">
            <component :is="getSortIcon('last_service_time')" />
          </el-icon>
        </template>
        <template #default="{ row }">
          <div>{{ row.lastServiceTime ?? '---' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #header>
          <span>创建时间</span>
          <el-icon @click="handleSort('create_time')">
            <component :is="getSortIcon('create_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #header>
          <span>更新时间</span>
          <el-icon @click="handleSort('update_time')">
            <component :is="getSortIcon('update_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column
        v-if="['管理员', '店长'].includes(userRole)"
        label="操作"
        fixed="right"
        width="180"
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            :icon="Edit"
            plain
            size="small"
            @click="handleEdit(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            plain
            size="small"
            @click="handleDelete(row)"
          ></el-button>
        </template>
      </el-table-column>
      <!-- 空数据提示 -->
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.pageNum"
      v-model:page-size="params.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="onPageSizeChange"
      @current-change="onPageNumChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </page-container>
  <!-- 抽屉 -->
  <car-edit ref="carEditRef" @success="handleReset"></car-edit>
</template>

<style lang="scss" scoped>
.tb {
  border-radius: 10px;
  box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}
</style>
